import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '', // 用户名
    avatar: ''  // 头像
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    // Object.assign(目标对象,源对象)实现将源对象合并到目标目录
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    // 从用户对象中解构出username用户名、password密码
    const { username, password,code } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password ,code:code}).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.tokenHead+" "+data.token)
        setToken(data.tokenHead+" "+data.token)
        resolve()

        // 为登录名赋值
        commit('SET_NAME', username)
        // 为头像赋值
        commit('SET_AVATAR', data.avatar)
 
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().
        then(data => {
          if (!data) {
            return reject('Verification failed, please Login again.')
          }
          const { name, userFace } = data
          // 给state中name用户名赋值
          commit('SET_NAME', name)
          // 给state中avatar用户头像赋值
          commit('SET_AVATAR', userFace)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })

  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        commit('menu/RESET_ROUTERS', {}, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

